const express = require('express');
// 创建一个路由
const router = express.Router();
const mysql = require('../conn');


// 登录
router.post('/login', (req, res) => {
    let { account, password } = req.body;
    // console.log(req.body);
    // res.send('接口测试成功');
    // 定义一个对象来接收我们返回给前端的数据
    let obj = {};
    // 数据库的增加语句
    let sql = `select account,password from admin`;

    mysql.query(sql, (err, results) => {
        if (err) return console.log(err);
        if (results.some(item => item.account === account)) {
            if (results.some(item => JSON.stringify(item) === JSON.stringify({
                "account": account,
                "password": password
            }))) {
                // console.log("jsonObject 存在于数组中");  
                obj.code = 0;
                obj.desc = '登录成功';
                obj.data = results;

            } else {
                // console.log("jsonObject 不存在于数组中");  
                obj.code = 2;
                obj.desc = '密码错误';
            }
        } else {
            obj.code = 3;
            obj.desc = '用户不存在';
        }

        res.send(obj);
    });
});
// 注册
router.post('/register', (req, res) => {
    let { account, password } = req.body;
    // console.log(req.body);
    // res.send('接口测试成功');
    // 定义一个对象来接收我们返回给前端的数据
    let obj = {};
    // 数据库的增加语句
    mysql.query("select account from admin", (err, results1) => {
        if (results1.some(item => item.account === account)) {
            obj.code = 1;
            obj.desc = '用户已注册过，不能重复注册';
            res.send(obj);
        } else {
            let sql = `insert into admin (account,password) value (?,?)`;
            mysql.query(sql, [account, password], (err, results) => {
                if (err) return console.log(err);

                obj.code = 0;
                obj.desc = '注册成功';
                obj.data = results;
                res.send(obj);
            });
        }
    })
});
module.exports = router;